package com.zhuoyue.biz.core.api.service.impl;

import java.util.HashMap;
import java.util.Map;

import com.zhuoyue.biz.core.api.dao.LocalSceneDao;
import com.zhuoyue.biz.core.api.domain.LocalSceneDO;

import com.zhuoyue.common.exception.ErrorType;
import com.zhuoyue.common.exception.ZyServerException;
import com.zhuoyue.common.utils.CmdUtils;
import com.zhuoyue.common.utils.DistributedLink;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.zhuoyue.biz.core.api.service.GatewayRedisService;

import com.zhuoyue.common.constant.DeviceConstant;


/**
 * @author wjming
 */
@Service("gatewayRedisService")
@Slf4j
public class GatewayRedisServiceImpl implements GatewayRedisService {

    @Value("${topic.rabbit.gatewayWriteChannel}")
    private String gatewayWriteChannel;

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private LocalSceneDao localSceneDao;

    private static final String HEADER_2A = "2A";
    private static final String END_23 = "23";

    /**
     * 新数据发送
     *
     * @param mac
     * @param data
     */
    @Override
    public void writeDataToGateway(String mac, String data) {
//        String message = makeGatewayWriteDataMessage(mac, data);
        if (!StringUtils.startsWithIgnoreCase(data, HEADER_2A) || !StringUtils.endsWithIgnoreCase(data, END_23)) {
            data = HEADER_2A + CmdUtils.getDateLength(data) + data + CmdUtils.getCmdBodySum(data) + END_23;
        }
        try {
            /**
             *从jedis连接池中获取jedis对象
             */
            Object channel = redisTemplate.opsForValue().get(mac + "_channel");
            if (channel == null) {
                throw new ZyServerException(ErrorType.Service_Fail.getCode(), "未连接到网关,请检查您的网络");
            }
            Map<String, Object> frameAndChannel = new HashMap<>(2);
            frameAndChannel.put("frame", data);
            frameAndChannel.put("channelLongId", channel);
            frameAndChannel.put("traceId", DistributedLink.getId());

            rabbitTemplate.convertAndSend(gatewayWriteChannel, frameAndChannel);
            log.info("gateway:{} , cmd:[{}]", mac, data);
        } catch (Exception e) {
//            throw new ZyServerException(ErrorType.Service_Fail.getCode(), e.getMessage());
        }

    }


//    @Override
//    public void writeDataToGateway(String mac, String data) {
//        String message = makeGatewayWriteDataMessage(mac, data);
//        try {
//            /**
//             *从jedis连接池中获取jedis对象
//             */
//            redisTemplate.convertAndSend(DeviceConstant.KEY_GATEWAY_DATA_WRITE_NOTIFY_CHANNEL, message);
//
//        } catch (Exception e) {
//
//            throw new ZyServerException(ErrorType.OBJECT_NOT_FOUND.getCode(), "数据发送异常");
//        }
//    }

    @Override
    public void sceneTriggerFrame(String id) {
        LocalSceneDO localSceneDO = localSceneDao.selectById(id);
        String cmd = "5000" + localSceneDO.getGatewayMac() + "0209" + CmdUtils.intToHexTwo(localSceneDO.getCode());
        cmd = "2A" + CmdUtils.getDateLength(cmd) + cmd + CmdUtils.getCmdBodySum(cmd) + "23";
        writeDataToGateway(localSceneDO.getGatewayMac(), cmd);
    }

    private String makeGatewayWriteDataMessage(String mac, String data) {
        Map<String, Object> map = new HashMap<>(4);
        map.put("type", DeviceConstant.MESSAGE_TYPE_WRITE_DATA_TO_GATEWAY);
        //字符串小写转化为大写
        map.put("mac", mac.toUpperCase());
        //指令
        map.put("data", data);
        map.put("time", System.currentTimeMillis() / 1000);
        return JSONObject.toJSONString(map);
    }

}
